package com.kaede.hayate.mybatisplus.plugins;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Date;

public class AutoFillMetaObjectHandler extends MetaObjectHandler {

	private Long errorUserId = -10000L;

	@Override
	public void insertFill(MetaObject metaObject) {
		// 自动填入创建人、创建日期、修改人、修改日期
		Date now = new Date();
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if(authentication != null && authentication.isAuthenticated()
				&& authentication instanceof UsernamePasswordAuthenticationToken){
			setFieldValByName("createBy", authentication.getCredentials(), metaObject);
			setFieldValByName("updateBy", authentication.getCredentials(), metaObject);
		}else {
			setFieldValByName("createBy",errorUserId, metaObject);
			setFieldValByName("updateBy",errorUserId, metaObject);
		}
        setFieldValByName("createDate", now, metaObject);
		setFieldValByName("updateDate", now, metaObject);
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		// 修改人、修改日期
		Date now = new Date();
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if(authentication != null && authentication.isAuthenticated()
				&& authentication instanceof UsernamePasswordAuthenticationToken){
			setFieldValByName("updateBy", authentication.getCredentials(), metaObject);
		}else {
			setFieldValByName("updateBy",errorUserId, metaObject);
		}
		setFieldValByName("updateDate", now, metaObject);
	}

}
